<script lang="ts" setup>
import type { CreateOrUpdateTableRequestData, TableData } from "@@/apis/tables/type"
import type { FormInstance, FormRules } from "element-plus"

import { createTableDataApi, deleteTableDataApi, getTableDataApi, updateTableDataApi, adminorderfetchShop } from "@@/apis/order"


import { usePagination } from "@@/composables/usePagination"
import { CirclePlus, Delete, Download, Refresh, RefreshRight, Search } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"
// import { adminorderfetchShop } from "../../../common/apis/order"

defineOptions({
  // 命名当前组件
  name: "ElementPlus"
})


const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// #region 增
const DEFAULT_FORM_DATA: CreateOrUpdateTableRequestData = {
  id: undefined,
  username: "",
  password: ""
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateTableRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<CreateOrUpdateTableRequestData> = {
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  password: [{ required: true, trigger: "blur", message: "请输入密码" }]
}
function handleCreateOrUpdate() {
  formRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("表单校验不通过")
      return
    }
    loading.value = true
    const api = formData.value.id === undefined ? createTableDataApi : updateTableDataApi
    api(formData.value).then(() => {
      ElMessage.success("操作成功")
      dialogVisible.value = false
      getTableData()
    }).finally(() => {
      loading.value = false
    })
  })
}
function resetForm() {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
// #endregion

// #region 删
function handleDelete(row: TableData) {
  ElMessageBox.confirm(`正在删除用户：${row.username}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
// #endregion

// #region 改
function handleUpdate(row: TableData) {
  dialogVisible.value = true
  formData.value = cloneDeep(row)
}
// #endregion

// #region 查
const tableData = ref<TableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  username: "",
  phone: "",
  countries: "",
  lang: "",
})
function getTableData() {
  loading.value = true
  getTableDataApi({
    currentPage: paginationData.currentPage,
    size: paginationData.pageSize,
    username: searchData.username,
    phone: searchData.phone
  }).then(({ data }) => {

    paginationData.total = data.total
    tableData.value = data.data
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    loading.value = false
  })
}
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}
// #endregion

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })



// 国家
const countries = [
  {
    "id": 10,
    "country_name": "澳大利亚",
    "currency_name": "AUD",
    "currency_symbol": "A$"
  },
  {
    "id": 9,
    "country_name": "俄罗斯",
    "currency_name": "RUB",
    "currency_symbol": "₽"
  },
  {
    "id": 8,
    "country_name": "日本",
    "currency_name": "JPY",
    "currency_symbol": "¥"
  },
  {
    "id": 7,
    "country_name": "英国",
    "currency_name": "GBP",
    "currency_symbol": "£"
  },
  {
    "id": 6,
    "country_name": "印尼",
    "currency_name": "IDR",
    "currency_symbol": "Rp"
  },
  {
    "id": 5,
    "country_name": "墨西哥",
    "currency_name": "MXN",
    "currency_symbol": "$"
  },
  {
    "id": 4,
    "country_name": "巴西",
    "currency_name": "BRL",
    "currency_symbol": "R$"
  },
  {
    "id": 3,
    "country_name": "欧盟",
    "currency_name": "EUR",
    "currency_symbol": "€"
  },
  {
    "id": 2,
    "country_name": "美国",
    "currency_name": "USD",
    "currency_symbol": "$"
  },
  {
    "id": 1,
    "country_name": "中国台湾",
    "currency_name": "TWD",
    "currency_symbol": "NT$"
  }
];
// 语言
const languages = [
  {
    "id": 9,
    "language": "繁体中文-台湾"
  },
  {
    "id": 10,
    "language": "英语-美国"
  },
  {
    "id": 12,
    "language": "英语-英国"
  },
  {
    "id": 13,
    "language": "德语-欧盟"
  },
  {
    "id": 14,
    "language": "日语-日本"
  },
  {
    "id": 15,
    "language": "法语-欧盟"
  },
  {
    "id": 17,
    "language": "葡萄牙语-巴西"
  },
  {
    "id": 18,
    "language": "西班牙语-欧盟"
  },
  {
    "id": 19,
    "language": "葡萄牙语-欧盟"
  },
  {
    "id": 21,
    "language": "英语-欧盟"
  },
  {
    "id": 23,
    "language": "意大利语-欧盟"
  },
  {
    "id": 24,
    "language": "希腊语-欧盟"
  },
  {
    "id": 26,
    "language": "印尼语-印尼"
  },
  {
    "id": 27,
    "language": "英语-墨西哥"
  },
  {
    "id": 28,
    "language": "俄语-俄罗斯"
  },
  {
    "id": 29,
    "language": "英语-澳大利亚"
  }
];
// 店铺
let shopList = [];

// 商品
let goodList = [
  {
    "id": 639,
    "agent_id": 29,
    "shop_id": 199,
    "goods_title": "小星星",
    "goods_title_zh": "小星星",
    "goods_img": "https:\/\/file.web3link.pro\/cloudfile\/shop\/20250513\/cvGzewTF7SD8XlqFrbfxNcgQn1js88eyLqqhbhT4.png",
    "goods_price": "63.00",
    "language_id": 29,
    "country_id": 10,
    "state": 1,
    "create_time": "2025-05-13 17:57:31",
    "update_time": "2025-05-13 17:57:31"
  }
];

// 支付
const payList = [
  {
    "id": 15,
    "mark": "paypal7aud",
    "pay_name": "Paypal澳大利亚AUD 最大5000美元 - 新通道",
    "min": 1,
    "max": 1000000000,
    "pay_status": "1",
    "pay_class": "App\\Lib\\Pay\\Channel\\PaypalXopay",
    "country_id": 10,
    "merchant_no": "682204da60b2f9a181c94bc6",
    "merchant_key": "a717159ba3c14334824a83491099dac4",
    "request_host": "https:\/\/api.xoxpay.net\/api\/v1\/paypal\/pay",
    "ext1": "AUD",
    "ext2": "",
    "remark": "",
    "create_time": "2025-05-13 17:31:40",
    "update_time": "2025-05-13 17:31:40"
  },
  {
    "id": 9,
    "mark": "paypal_aud",
    "pay_name": "Paypal澳大利亚AUD 最大5000美元",
    "min": 1,
    "max": 1000000000,
    "pay_status": "1",
    "pay_class": "App\\Lib\\Pay\\Channel\\PaypalWP",
    "country_id": 10,
    "merchant_no": "121212B",
    "merchant_key": "guFVzWMPXM7jAzHael8RpfG5fVDn1XJ9Yt6c3UdOpXasvT1yZIg7LElsNkCPmNt8HGB5bQUoBwrKnv4s9UlkEAYxJd0iwadJvd7XO6FOUnXQ3wiED4L0R4czRYZ9ZuTEGgYlwQ6sSNuvVZhyL0SbViTzNo63prhWeDBhrtS9SLIpHY3ArgICTb17W3xypjHhFPk584cRJmk82wbOVqFml9cgF2aoWBiyyq7fJho2irutN4MSsojAjHkxCEtKGq5nRmbTeWnePf1BqGxaOeKDzQujCQ0MC8I2KmD2AKPxd5UI",
    "request_host": "https:\/\/net.mrphper.xyz\/pay\/create_payment",
    "ext1": "AUD",
    "ext2": "",
    "remark": "",
    "create_time": "2025-04-17 00:47:40",
    "update_time": "2025-05-13 03:30:26"
  }
]

adminorderfetchShop({
  country_id: '10',
  language_id: '29'
}).then((res) => {
  shopList = res.data
})

// 查看连接
const seeUrl = () => {
  console.log('查看连接');
}

const dialogTableVisible = ref(false)
const gridData = [
  {
    "id": 10,
    "name": "美国Doordash7 - 如果支付方式是贝宝，请代理不要点击支付，否则会触发风控",
    "path": "https:\/\/doordsahy.com\/do\/",
    "status": 1,
    "create_time": "2025-04-30 00:44:02",
    "update_time": "2025-05-13 04:14:47"
  },
  {
    "id": 9,
    "name": "美国Doordash 6 - 如果支付方式是贝宝，请代理不要点击支付，否则会触发风控",
    "path": "https:\/\/doordsahai.com\/do\/",
    "status": 1,
    "create_time": "2025-04-30 00:43:40",
    "update_time": "2025-05-13 04:14:53"
  },
  {
    "id": 8,
    "name": "美国Doordash 5 - 如果支付方式是贝宝，请代理不要点击支付，否则会触发风控",
    "path": "https:\/\/doordsah.store\/do\/",
    "status": 1,
    "create_time": "2025-04-30 00:43:11",
    "update_time": "2025-05-13 04:14:57"
  },
  {
    "id": 4,
    "name": "美国Doordash 1 - 如果支付方式是贝宝，请代理不要点击支付，否则会触发风控",
    "path": "https:\/\/doordash-isp.com\/do\/",
    "status": 1,
    "create_time": "2025-03-28 10:14:44",
    "update_time": "2025-05-13 04:15:01"
  }
]
const copyUrl = (data) => {
  console.log(data, 'data');
  navigator.clipboard.writeText(data).then(function () {
    alert("已复制");
  }).catch(function (error) {
    alert("复制失败: " + error);
  });
}



</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="username" label="订单号">
          <el-input v-model="searchData.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="type" label="状态" placeholder="" style="width: 200px;">
          <el-select v-model="searchData.type" placeholder="" style="width: 200px;">
            <el-option v-for="item in [
              {
                label: '未支付', value: 1
              },
              {
                label: '已支付', value: 2
              },
              {
                label: '部分支付', value: 3
              },
              {
                label: '支付失败', value: 4
              },
            ]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="username" label="上级ID">
          <el-input v-model="searchData.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">
            新增订单
          </el-button>
          <!-- <el-button type="danger" :icon="Delete">
            批量删除
          </el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="expand">
            <template #default="props">
              <div m="4">
                <el-table :data="props.row.goods">
                  <el-table-column label="商品标题" prop="goods_title" />
                  <el-table-column label="商品中文标题" prop="state" />
                  <el-table-column label="商品图片" prop="goods_img">
                    <template #default="scope">
                      <img :src="scope.row.goods_img" style="width: 50px;height: 50px;" alt="">
                    </template>
                  </el-table-column>
                  <el-table-column label="数量" prop="goods_num" />
                  <el-table-column label="商品价格" prop="all_price" />
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="agent.username" label="代理名" align="center" />
          <el-table-column prop="order_id" label="订单ID" align="center" />
          <el-table-column prop="rewrite_order_id" label="重写订单号" align="center" />
          <el-table-column prop="server_price" label="服务费" align="center" />
          <el-table-column prop="order_url" label="订单链接" align="center" width="150">
            <el-button type="success" @click="dialogTableVisible = true">
              查看连接
            </el-button>
          </el-table-column>
          <el-table-column prop="arrival_price" label="环保费" align="center" />
          <el-table-column prop="order_price" label="订单总额" align="center" />
          <el-table-column prop="arrival_price" label="到账金额" align="center" />
          <el-table-column prop="rate" label="佣金比例" align="center" />
          <el-table-column prop="commission" label="佣金" align="center" />
          <el-table-column prop="pay_id" label="支付方式" align="center" />
          <el-table-column prop="delivery_method" label="配送类型" align="center" />
          <el-table-column prop="receive_name" label="收货人姓名" align="center" />
          <el-table-column prop="receive_phone" label="收货人电话" align="center" />
          <el-table-column prop="receive_address" label="收货人地址" align="center" />
          <el-table-column prop="create_time" label="创建时间" align="center" />
          <el-table-column prop="update_time" label="更新时间" align="center" />
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination background :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
          :total="paginationData.total" :page-size="paginationData.pageSize" :current-page="paginationData.currentPage"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible" :title="formData.id === undefined ? '创建订单' : '修改订单'" width="30%"
      @closed="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <!-- 国家 -->
        <el-form-item prop="country_id" label="国家">
          <el-select v-model="formData.country_id" placeholder="">
            <el-option v-for="item in countries" :key="item.id" :label="item.country_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 语言 -->
        <el-form-item prop="language_id" label="语言">
          <el-select v-model="formData.language_id" placeholder="">
            <el-option v-for="item in languages" :key="item.id" :label="item.language" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 店铺 -->
        <el-form-item prop="shop_id" label="店铺">
          <el-select v-model="formData.shop_id" placeholder="">
            <el-option v-for="item in shopList" :key="item.id" :label="item.shop_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 商品 -->
        <el-form-item prop="goods_ids" label="商品">
          <el-select v-model="formData.goods_ids" placeholder="" multiple>
            <el-option v-for="item in goodList" :key="item.id" :label="item.goods_title" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 支付 -->
        <el-form-item prop="pay_id" label="支付">
          <el-select v-model="formData.pay_id" placeholder="">
            <el-option v-for="item in payList" :key="item.id" :label="item.pay_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!--  -->
        <el-form-item prop="server_price" label="服务费">
          <el-input v-model="formData.server_price" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="hb_price" label="环保费">
          <el-input v-model="formData.hb_price" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="delivery_price" label="配送费">
          <el-input v-model="formData.delivery_price" placeholder="请输入" />
        </el-form-item>
        <!-- 配送类型 -->
        <el-form-item prop="delivery_method" label="配送类型">
          <el-select v-model="formData.delivery_method" placeholder="">
            <el-option v-for="item in [
              {
                label: '快速', value: 1
              },
              {
                label: '标准', value: 2
              },
              {
                label: '慢速', value: 3
              },
            ]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 收货信息 -->
        <el-form-item prop="receive_name" label="收货人姓名">
          <el-input v-model="formData.receive_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="receive_phone" label="收货人电话">
          <el-input v-model="formData.receive_phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="receive_address" label="收货人地址">
          <el-input v-model="formData.receive_address" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleCreateOrUpdate">
          确认
        </el-button>
      </template>
    </el-dialog>
    <!-- 查看连接 -->
    <el-dialog v-model="dialogTableVisible" title="查看订单链接">
      <el-table :data="gridData">
        <el-table-column property="name" label="模版名称" />
        <el-table-column property="path" label="订单链接" />
        <el-table-column property="address" label="	操作">
          <template #default="scope">
            <el-button type="success" @click="copyUrl(scope.row.path)">
              复制连接
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.el-alert {
  margin-bottom: 20px;
}

.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>